const Service = require('egg').Service;

class TableService extends Service {
	tableName = 'mock-server-table';
	// 查询
	async queryTable() {
		const { ctx, app } = this;
		const productId = ctx.request.header['product-id'];
		console.log('====productId===', productId);
		const res = await app.mongo.find(this.tableName, {
			query: { productId }
		});
		return res;
	}
	// 创建表
	async createTable(data) {
		const { ctx, app } = this;
		const productId = ctx.request.header['product-id'];
		const createTime = ctx.helper.getCurrentTime();
		const res = await app.mongo.insertOne(this.tableName, {
			doc: { createTime, productId, ...data }
		});
		return res;
	}
	// 更新表
	async updateTable() {}
	// 删除表
	async deleteTable(id) {
		const { ctx, app } = this;
		const productId = ctx.request.header['product-id'];
		const _id = app.getObjectId(id);
		const createTime = ctx.helper.getCurrentTime();
		// 找到这个表，看下是否有其他引用，如果有则不能删除
		const table = await app.mongo.findOne(this.tableName, {
			query: { _id }
		});
		if (table) {
			const tableInfo = await app.mongo.find(table.name, {});
			if (tableInfo.length > 0) {
				// 说明有引用，则不能删除
				throw new HttpException(401, '此表有接口引用，无法删除');
			}
		}
		const res = await app.mongo.findOneAndDelete(this.tableName, {
			filter: { _id }
		});
		return res;
	}
}

module.exports = TableService;
